package com.jxsa.config;

import com.jxsa.point.CustomAccessDeniedHandler;
import com.jxsa.point.CustomAuthenticationEntryPoint;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import javax.annotation.Resource;

/**
 * @author pwq
 */
@Configuration
@EnableResourceServer
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerConfiguration extends ResourceServerConfigurerAdapter {

    @Resource
    private CustomAuthenticationEntryPoint customAuthenticationEntryPoint;
    @Resource
    private CustomAccessDeniedHandler customAccessDeniedHandler;

    @Override
    public void configure(HttpSecurity http) throws Exception {
        http.csrf().disable();
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
        http.authorizeRequests()
                .antMatchers("/order/**").hasAuthority("ADMIN");
    }


    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.authenticationEntryPoint(customAuthenticationEntryPoint);
        resources.accessDeniedHandler(customAccessDeniedHandler);
        resources.tokenServices(tokenService());
        resources.tokenServices(userTokenService());

    }

    @Bean
    public ResourceServerTokenServices tokenService() {
        RemoteTokenServices service = new RemoteTokenServices();
        service.setClientId("client_1");
        service.setClientSecret("123456");
        service.setCheckTokenEndpointUrl("http://localhost:8080/oauth/check_token");
        return service;
    }

    @Bean
    @Primary
    public ResourceServerTokenServices userTokenService() {
        return new UserInfoTokenServices("http://localhost:8080/user/info","client_1");
    }

}
